package com.mf.morefun.ui.moreread;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.EventMessageBean;
import com.mf.morefun.bean.ListenOriginalBean;
import com.mf.morefun.bean.LocalListenBean;
import com.mf.morefun.bean.MfPicaudioRelListBean;
import com.mf.morefun.bean.MfimgListBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.requestbean.RequestAchievementBean;
import com.mf.morefun.service.ListenOriginalService;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.mf.morefun.util.DownloadUtils;
import com.mf.morefun.util.GetUserInfo;
import com.mf.morefun.util.IsLoginBean;
import com.mf.morefun.util.SendStarOrFlowerNet;
import com.mf.morefun.widget.NetErrorPop;
import com.mf.morefun.widget.RoundProcessDialog;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/*
听原音
 */
public class ListenOriginalActivity extends BaseBusActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.vp_info)
    ViewPager vpInfo;
    @BindView(R.id.pb_speed)
    ProgressBar pbSpeed;
    @BindView(R.id.iv_play)
    ImageView ivPlay;
    @BindView(R.id.iv_reListen)
    ImageView ivReListen;
    @BindView(R.id.ly_content)
    LinearLayout lyContent;
    private String bookId = "";
    private DbManager manager;
    private List<View> viewContains = new ArrayList<View>();//viewpager容器
    private int currentPosition = 0;
    private MyPagerAdapter myPagerAdapter;
    private int totalPage = 0;
    private ListenOriginalService mListenOriginalService = null;
    private List<LocalListenBean> mLocalViewList = new ArrayList<>();//重新创建一个集合来存排序好的集合
    private String bookName = "";
    private RoundProcessDialog dialog;
    private SendStarOrFlowerNet mSendStartOrFlowerNet;
    private boolean isCanPlay = true;
    private String userId = "";
    PowerManager powerManager = null;
    PowerManager.WakeLock wakeLock = null;
    private SPUtils mSPUtils;

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_listenoriginal;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        powerManager = (PowerManager)this.getSystemService(this.POWER_SERVICE);
        wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
        userId = getIntent().getStringExtra(Configuration.USERID);
        mSPUtils = new SPUtils(ListenOriginalActivity.this);
        if (!IsLoginBean.isNo(false)) {
            GetUserInfo.initLogin(mSPUtils.getString(Configuration.USERPHONE), mSPUtils.getString(Configuration.USERPASSWORD));
        }
        dialog = new RoundProcessDialog(ListenOriginalActivity.this, "");
        EventBus.getDefault().register(this);
        manager = x.getDb(MoreFunApplication.daoConfig);
        bookId = getIntent().getStringExtra("BOOKID");
        if (StringUtils.isEmpty(getIntent().getStringExtra("BOOKNAME"))) {
            bookName = "" + System.currentTimeMillis();
        } else {
            bookName = getIntent().getStringExtra("BOOKNAME") + "original";
        }
        if (!StringUtils.isEmpty(bookId)) {
            initListenOriginal();
        }
        ivReListen.getBackground().setAlpha(100);
    }

    private void initListenOriginal() {
        if (null != dialog && !dialog.isShow()) {
            dialog.show();
        }
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.LISTENORIHINAL);
        RequestAchievementBean requestAchievementBean = new RequestAchievementBean();
        requestAchievementBean.setId(bookId);
        params.setBodyContent(JSON.toJSONString(requestAchievementBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            ListenOriginalBean listenOriginalBean = JSON.parseObject(resultBean.getResult(), ListenOriginalBean.class);
                            if (!StringUtils.isEmpty(listenOriginalBean.getImgList()) && !StringUtils.isEmpty(listenOriginalBean.getImgAudioRelList())) {
                                List<MfimgListBean> mfimgListBeanList = JSON.parseArray(listenOriginalBean.getImgList(), MfimgListBean.class);
                                List<MfPicaudioRelListBean> mfPicaudioRelListBeanList = JSON.parseArray(listenOriginalBean.getImgAudioRelList(), MfPicaudioRelListBean.class);
                                //两个集合必须都不为空
                                if (null != mfimgListBeanList && mfimgListBeanList.size() > 0 && null != mfPicaudioRelListBeanList && mfPicaudioRelListBeanList.size() > 0) {
                                    //必须等于  因为一对一
                                    if (mfimgListBeanList.size() == mfPicaudioRelListBeanList.size()) {
                                        //组装成自己的对象
                                        List<LocalListenBean> mLocalList = new ArrayList<>();
                                        for (int i = 0; i < mfimgListBeanList.size(); i++) {
                                            LocalListenBean localListenBean = new LocalListenBean();
                                            localListenBean.setImageUrl(mfimgListBeanList.get(i).getAddress());
                                            localListenBean.setLocalListenUrl("");
                                            if (null != listenOriginalBean.getAudioList()){
                                                localListenBean.setNetListenUrl(listenOriginalBean.getAudioList().get(0).getAddress());
                                            }
                                            localListenBean.setVodStart(mfPicaudioRelListBeanList.get(i).getVodStart());
                                            localListenBean.setMusicName(bookName);
                                            localListenBean.setId(0);
                                            mLocalList.add(localListenBean);
                                        }
                                        //先判断是否要去下载 本地有了就不需要下载
                                        showLocalList(mLocalList);


                                    }
                                }
                            } else {
                                ToastUtils.show(getApplicationContext(), "数据为空", 100);
                            }
                        } else {
                            ToastUtils.show(getApplicationContext(), "数据为空", 100);
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (null != dialog && dialog.isShow()) {
                    dialog.cancel();
                }
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(ListenOriginalActivity.this);
                    errorPop.showPop("");
                    break;
                case 100:
                    vpInfo.setCurrentItem(currentPosition);
                    break;
            }
        }
    };

    private void showLocalList(List<LocalListenBean> mLocalList) {
        try {
            List<LocalListenBean> localList = manager.selector(LocalListenBean.class).where("netListenUrl", "==", mLocalList.get(0).getNetListenUrl()).findAll();
            if (null != localList && localList.size() > 0) {
                manager.delete(localList);
                removeDuplicate(localList);
                List<LocalListenBean> mNeedList = new ArrayList<>();
                for (int i = 0; i < localList.size(); i++) {
                    manager.save(localList.get(i));
                    if (mLocalList.get(0).getNetListenUrl().equals(localList.get(i).getNetListenUrl())) {
                        mNeedList.add(localList.get(i));//拿到存在本地的
                    }
                }
                if (null != mNeedList && mNeedList.size() > 0) {
                    //这里拿到集合可以直接播放
                    ablePlay(mNeedList);
                } else {
                    //这里需要去下载
                    needDownload(mLocalList);
                }
            } else {
                //这里肯定是要去下载
                needDownload(mLocalList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void removeDuplicate(List<LocalListenBean> localMessageList) {
        List<LocalListenBean> newList = new  ArrayList<LocalListenBean>();
        for(LocalListenBean msg : localMessageList){
            if (newList.size() > 0){
                if (!isSure(newList, msg.getImageUrl())){
                    newList.add(msg);
                }
            }else {
                newList.add(msg);
            }
        }
        localMessageList.clear();
        localMessageList.addAll(newList);
    }

    private boolean isSure(List<LocalListenBean> newList, String imageUrl) {
        boolean isHave = false;
        for (LocalListenBean newMsg : newList){
            if (newMsg.getImageUrl().equals(imageUrl)){
                isHave = true;
            }
        }
        return isHave;
    }

    //需要去下载的集合
    private void needDownload(List<LocalListenBean> mLocalList) {
        DownloadUtils.getsInstance().setListener(new DownloadUtils.OnDownloadListener() {
            @Override
            public void onDowload(String mp3Url) {
                //把本地地址加上 存进入数据库
                insertDb(mp3Url, mLocalList);
                ablePlay(mLocalList);

                //下载完成
            }

            @Override
            public void onFailed(String error) {
                ToastUtils.show(getApplicationContext(), error, 100);
            }
        }).download(mLocalList.get(0));
    }

    private void insertDb(String mp3Url, List<LocalListenBean> mLocalList) {
        try {
            for (int i = 0; i < mLocalList.size(); i++) {
                mLocalList.get(i).setLocalListenUrl(mp3Url);
                manager.save(mLocalList.get(i));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //能够播放的集合   但是还要调整集合顺序
    private void ablePlay(List<LocalListenBean> mNeedList) {
        //先初始化一个集合  排序
        getVodStartList(mNeedList, mLocalViewList);
        //同时还要展示viewpager
        showViewPager(mLocalViewList);
    }

    private void getVodStartList(List<LocalListenBean> mNeedList, List<LocalListenBean> mLocalList) {
        double mVodArray[] = new double[mNeedList.size()];
        for (int i = 0; i < mNeedList.size(); i++) {
            mVodArray[i] = mNeedList.get(i).getVodStart();
        }
        //冒泡排序一下
        bubbleSort(mVodArray);
        for (int i = 0; i < mVodArray.length; i++) {
            //取到对象
            getNeedBean(mVodArray[i], mNeedList, mLocalList);
        }
    }

    private void getNeedBean(double vod, List<LocalListenBean> mNeedList, List<LocalListenBean> mLocalList) {
        for (int i = 0; i < mNeedList.size(); i++) {
            if (vod == mNeedList.get(i).getVodStart()) {
                mLocalList.add(mNeedList.get(i));
            }
        }
    }

    private void bubbleSort(double[] mVodArray) {
        for (int i = 0; i < mVodArray.length - 1; i++) {
            for (int j = 0; j < mVodArray.length - 1 - i; j++) {
                if (mVodArray[j] > mVodArray[j + 1]) {
                    double temp;
                    temp = mVodArray[j];
                    mVodArray[j] = mVodArray[j + 1];
                    mVodArray[j + 1] = temp;
                }
            }
        }
    }

    //开始进行播放展示图片
    private void showViewPager(List<LocalListenBean> mLocalList) {
        viewContains.clear();
        currentPosition = 0;
        setPagerAdapter();
        setPagerListener();
        if (null != mLocalList && mLocalList.size() > 0) {
            totalPage = mLocalList.size();
            for (int i = 0; i < mLocalList.size(); i++) {
                View view = LayoutInflater.from(ListenOriginalActivity.this).inflate(R.layout.layout_advertisement, null);
                ImageView imageView = view.findViewById(R.id.iv_image);
                Glide.with(getApplicationContext()).load(mLocalList.get(i).getImageUrl()).into(imageView);
                viewContains.add(view);
            }
            myPagerAdapter.notifyDataSetChanged();
            setProgressBar(currentPosition);
            MoreFunApplication.isOut = false;//这里是进入
            Intent intent = new Intent();
            intent.setAction("GETMUSICPOSITION");
            intent.setPackage("com.mf.morefun"); //指定启动的是那个应用（lq.cn.twoapp）中的Action(b.aidl.DownLoadService)指向的服务组件
            startService(intent);
            mListenOriginalService = new ListenOriginalService(mLocalList.get(0).getLocalListenUrl());
            mListenOriginalService.play();

            if (null != dialog && dialog.isShow()) {
                dialog.cancel();
            }
        }
    }

    private void setPagerListener() {
        vpInfo.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setProgressBar(position);//更新进度条
                int mPosition = 0;
                if (position == 0) {
                    mPosition = position;
                } else {
                    mPosition = position - 1;
                }
                if (null != mListenOriginalService && null != mListenOriginalService.player && mLocalViewList.size() > 0) {
                    if (position == 0) {
                        mListenOriginalService.player.seekTo(0);
                    } else {
                        mListenOriginalService.player.seekTo((int) (mLocalViewList.get(mPosition).getVodStart() * 1000));
                    }
                    if (isCanPlay){
                        ivPlay.setImageResource(R.mipmap.zanting);
                        mListenOriginalService.goPlay();
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (null != mListenOriginalService){
                mListenOriginalService.pause();
            }
            ivPlay.setImageResource(R.mipmap.bofang);
            if (null != wakeLock){
                wakeLock.release();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (null != wakeLock){
                wakeLock.acquire();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void setProgressBar(int currentPosition) {
        int index = (100 / totalPage);
        if (currentPosition == (totalPage - 1)) {
            pbSpeed.setProgress(100);
        } else {
            pbSpeed.setProgress(index * (currentPosition + 1));
        }
    }

    private class MyPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return viewContains.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//                ((ViewPager) container).removeView(viewContains.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            position %= viewContains.size();
            if (position < 0) {
                position = viewContains.size() + position;
            }
            View view = viewContains.get(position);
            // 如果View已经在之前添加到了一个父组件，则必须先remove，否则会抛出IllegalStateException。
            ViewParent vp = view.getParent();
            if (vp != null) {
                ViewGroup parent = (ViewGroup) vp;
                parent.removeView(view);
            }
            container.addView(view);
            return view;
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }
    }


    private void setPagerAdapter() {
        myPagerAdapter = new MyPagerAdapter();
        vpInfo.setAdapter(myPagerAdapter);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mListenOriginalService) {
            mListenOriginalService.stop();
        }
        MoreFunApplication.isOut = true;//退出
        EventBus.getDefault().unregister(this);
        if (null != mSendStartOrFlowerNet){
            mSendStartOrFlowerNet.stopAnim();
        }
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.iv_back, R.id.iv_play, R.id.iv_reListen})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_play:
                if (null != mListenOriginalService && null != mListenOriginalService.player && null != mLocalViewList && mLocalViewList.size() > 0) {
                    if (!mListenOriginalService.player.isPlaying()) {
                        mListenOriginalService.goPlay();
                        ivPlay.setImageResource(R.mipmap.zanting);
                        isCanPlay = true;
                    } else if (mListenOriginalService.player.isPlaying()) {
                        mListenOriginalService.pause();
                        ivPlay.setImageResource(R.mipmap.bofang);
                    }
                }
                break;
            case R.id.iv_reListen:
                if (null != mListenOriginalService && null != mListenOriginalService.player && mLocalViewList.size() > 0) {
                    int mPosition = 0;
                    if (vpInfo.getCurrentItem() == 0) {
                        mPosition = vpInfo.getCurrentItem();
                    } else {
                        mPosition = vpInfo.getCurrentItem() - 1;
                    }
                    if (vpInfo.getCurrentItem() == 0) {
                        mListenOriginalService.player.seekTo(0);
                    } else {
                        mListenOriginalService.player.seekTo((int) (mLocalViewList.get(mPosition).getVodStart() * 1000));
                    }
                    mListenOriginalService.goPlay();
                    ivPlay.setImageResource(R.mipmap.zanting);
                    isCanPlay = true;
                }
                break;
        }
    }

    //接受musicService发过来的消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMusicMessage(EventMessageBean message) {
        if (message.getType() == 0) {
            isCanPlay = false;
            ivPlay.setImageResource(R.mipmap.bofang);
            vpInfo.setCurrentItem(0);
            //
            mSendStartOrFlowerNet = new SendStarOrFlowerNet(ListenOriginalActivity.this, lyContent);
            mSendStartOrFlowerNet.initGetFlower(20
                    ,userId,
                    bookId,
                    "1", "6");
        } else if (message.getType() == 1) {
            ivPlay.setImageResource(R.mipmap.bofang);
            ToastUtils.show(ListenOriginalActivity.this, "音乐文件加载失败", 100);
        } else {
            if (null != mListenOriginalService && null != mListenOriginalService.player && mListenOriginalService.player.isPlaying()) {
                long second = mListenOriginalService.player.getCurrentPosition();
                int position = currentPosition;
                //获得比例
                if (null != mLocalViewList && mLocalViewList.size() > 0) {
                    for (int i = 0; i < mLocalViewList.size(); i++) {
                        if (i == 0) {
                            if (second >= 0 && second < (int) (mLocalViewList.get(i).getVodStart() * 1000)) {
                                currentPosition = 0;
                            }
                        } else if (second >= (int) (mLocalViewList.get(i - 1).getVodStart() * 1000) && second < (int) (mLocalViewList.get(i).getVodStart() * 1000)) {
                            currentPosition = i;
                        }
                    }
                }
                if (position != currentPosition) {
                    mHandler.sendEmptyMessageDelayed(100, 1500);
                    if (null != mListenOriginalService && null != mListenOriginalService.player){
                        mListenOriginalService.pause();
                        ivPlay.setImageResource(R.mipmap.bofang);
                    }
                }
            }
        }
    }

    private String formatTime(long time) {
        return formatTime("mm:ss", time);
    }

    private String formatTime(String pattern, long milli) {
        int m = (int) (milli / DateUtils.MINUTE_IN_MILLIS);
        int s = (int) ((milli / DateUtils.SECOND_IN_MILLIS) % 60);
        String mm = String.format(Locale.getDefault(), "%02d", m);
        String ss = String.format(Locale.getDefault(), "%02d", s);
        return pattern.replace("mm", mm).replace("ss", ss);
    }

}
